<template>
    
  <!-- 加载状态提示 -->
  <div v-if="loading">加载中...</div>
  
  <!-- 错误提示 -->
  <div v-if="error" class="error">加载失败，请重试</div>
  
  <!-- 动态渲染加载后的组件 -->
  <component :is="asyncComponent" v-if="asyncComponent && !loading" />


</template>

<script setup lang="ts">

import { useRouter } from 'vue-router'
import { defineAsyncComponent, ref, onMounted } from 'vue';

const { currentRoute } = useRouter()
console.log('====> currentRoute value name', currentRoute.value.name)
const menuName = currentRoute.value.name?.toString();
const cmpName = menuName?.split('_')[0];
console.log('====> currentRoute ', currentRoute)

const loading = ref(true) // 列表的加载中

/** 初始化 **/
onMounted(() => {
  
  loadComponent("/admin-api/magic-cmp/script/" + cmpName, cmpName)
}) 


// 响应式变量
const asyncComponent = ref(null); // 保存动态加载的组件
const error = ref(false);         // 错误状态

// 点击按钮触发加载
const loadComponent = async (url, cmpName) => {
  if (asyncComponent.value) return; // 避免重复加载

  loading.value = true;
  error.value = false;

  try {
    // 动态插入 <script> 标签
    await new Promise((resolve, reject) => {
      const script = document.createElement('script');
      script.src = url; // 使用绝对路径
      script.onload = resolve;
      script.onerror = reject;
      document.head.appendChild(script);
    });
    if (!window.cmpFuncWrap) {
      window.cmpFuncWrap = {};
    }

    const MyComponent = window.cmpFuncWrap[cmpName]();

    // 假设 JS 文件将组件挂载到全局变量 window.MyComponent
    if (!MyComponent) {
      throw new Error('组件未正确导出');
    }

    // 将全局组件转换为 Vue 异步组件
    asyncComponent.value = defineAsyncComponent({
      loader: () => Promise.resolve(MyComponent),
      delay: 200,
      timeout: 3000
    });
  } catch (err) {
    error.value = true;
    console.error('加载失败:', err);
  } finally {
    loading.value = false;
  }
}

</script>
